<template>
  <div class="createPost-container " >

    <el-form :model="form" ref="form"  :rules="rules" class="form-container" >
      <div class="sub-navbar draft">
        <!--<CommentDropdown v-model="form.comment_disabled" />-->

        <el-button v-on:click="goback"  icon="el-icon-back" >返回</el-button>
        <el-button  @click.native="submitForm" :loading="addLoading" type="success" >发布</el-button>
        <!--<el-button v-loading="loading" type="warning" @click="draftForm">草稿</el-button>-->
        <el-button @click="resetForm('form')">重置</el-button>
      </div>
      <div class="createPost-main-container">
        <p class="warn-content">
          添加商品
        </p>
        <el-form-item label="商品名称：" :label-width="formLabelWidth" prop="spmc">
          <el-input v-model="form.spmc" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item  label="商品图片：" :label-width="formLabelWidth" pro="sptp">
          <el-upload   v-model="form.sptp"
                       class="upload-demo"
                       :on-preview="handlePreview"
                       :on-remove="handleRemove"
                       :on-success="handleAvatarSuccess"
                       :before-upload="beforeAvatarUpload"
                       :before-remove="beforeRemove"
                       multiple
                       :limit="3"
                       :on-exceed="handleExceed"
                       action="https://www.laidianba.net.cn:9600/uploadFile"
                       :file-list="fileList"
                       list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/gif/bmp文件，且不超过2M</div>
          </el-upload>

        </el-form-item>
        <el-form-item label="计量单位" :label-width="formLabelWidth" prop="jldw">
          <el-input v-model="form.jldw" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="联系电话" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="form.phone" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="外部链接" :label-width="formLabelWidth" prop="wblj">
          <el-input v-model="form.wblj" auto-complete="off"></el-input>
        </el-form-item>
      <!--  <el-form-item label="分类名称" :label-width="formLabelWidth" prop="spfl_mc">
          <el-input v-model="form.spfl_mc" auto-complete="off"></el-input>
        </el-form-item>-->
        <!--<el-form-item label="标签：" :label-width="formLabelWidth" prop="fxbq">
          &lt;!&ndash; <el-input v-model="form.fxbq" auto-complete="off">
           </el-input>&ndash;&gt;
          <el-tag
            size="medium"
            :key="tag"
            type=""
            v-for="tag in form.fxbqs"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)">
            {{tag}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            size="medium"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>

          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 新增标签</el-button>
        </el-form-item>-->

        <el-form-item label="商品价格：" :label-width="formLabelWidth" prop="spjg">
          <el-input v-model="form.spjg" type="number"   onkeypress="return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序号：" :label-width="formLabelWidth" prop="pxh">
          <el-input v-model="form.pxh" auto-complete="off"  type="number"  onkeypress="return( /[\d]/.test(String.fromCharCode(event.keyCode) ) )" placeholder="排序号请输入数字" ></el-input>
        </el-form-item>
        <el-form-item label="商品描述:" :label-width="formLabelWidth" prop="spms">
          <div class="editor-container">
            <Tinymce ref="editor" :height="800" v-model="form.spms" />
          </div>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('form')" style="float:right">重置</el-button>

        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
  import util from '@/common/js/util'
  import Tinymce from '@/components/Tinymce'
  import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './components/Dropdown'
  import { validateURL } from '@/utils/validate'
  import { getSpfls, addGoods,findGoodsById ,updateGoods} from '@/api/goods'
  import { delFile} from '@/api/image'

  export default {
    name: "editGoods",
    components: { Tinymce,CommentDropdown },
    data() {
      return {
        currentPage: 1,
        currentResult: 0,
        entityOrField: true,
        pageStr: 'string',
        pd: {
          zdbh: ''
        },
        showCount: 10,
        totalPage: 0,
        totalResult: 0,
        fileList: [],
        listLoading: true,
        loading: false,
        addLoading: false,
        spfls: [],

        dialogTableVisible: false,
        dialogFormVisible: false,
        form: {
          id:'',
          sptp:'',
          spjg: '',
          spms: '',
          spmc: '',
          pxh: '',
          spfl:'',
          spfl_mc:'',
          phone:'',
          jldw:'',
          wblj:''
        },
        rules: {
          spms: [
            { required: true, message: '请输入名称', trigger: 'blur' },
            { min: 1, max: 50, message: '最多可输入50个字', trigger: 'blur' }
          ],
          phone: [
            { required: true, message: '请输入联系电话', trigger: 'blur' },
            { min: 1, max: 12, message: '最多可输入12个字', trigger: 'blur' }
          ],
          spms: [
            { required: false, message: '请输入描述', trigger: 'blur' },
            { min: 1, max: 12000, message: '发现描述最多可输入6000个字（包含空格）', trigger: 'blur' }
          ],
          spjg: [
            { required: true, message: '请输入数字', trigger: 'blur' },
            { min: 1, max: 10, message: '最多可输入10个数字', trigger: 'blur' }
          ],
          pxh: [
            { required: false, message: '排序号只可以输入数字', trigger: 'blur' },
            { min: 1, max: 10, message: '最多可输入10个数字', trigger: 'blur' }
          ],
        },
        formLabelWidth: '120px',

        inputVisible: false,
        inputValue: ''

      }
    },
    created() {
      var param = this.$route.query;
      // var param = this.$route.params;
      this.form.id = param.id;
      console.log("params",param);
      if(JSON.stringify(param)!=='{}'){
        console.log('查询详情');
        this.getDetail()
      }

      this.fetchData()
    },
    methods: {
      handleClose(tag) {
        // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        this.form.fxbqs.splice(this.form.fxbqs.indexOf(tag), 1);
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          console.log('长度',inputValue.length);
          if(inputValue.length<10) {
            if (this.form.fxbqs.includes(inputValue) == false) {
              // console.log('不存在');
              if (this.form.fxbqs.length < 3) {
                this.form.fxbqs.push(inputValue);
              } else {
                this.$message({
                  message: '最多可添加3个标签',
                  type: 'error'
                })
              }
            } else {
              // console.log('已存在该标签');
              this.$message({
                message: '已存在该标签',
                type: 'error'
              })
            }
          }else {
            this.$message({
              message: '标签长度不能超过10个字',
              type: 'error'
            })
          }
        }
        this.inputVisible = false;
        this.inputValue = '';
      }
    ,

      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      getDetail(){
        const params = {id:this.form.id}
        this.listLoading = true
        findGoodsById(params).then(response => {
          if (response.data.reason === null) {
            this.form = Object.assign({}, response.data.result.GoodsOne);
            let sptp = response.data.result.GoodsOne.sptp;
            console.log('picture',sptp.split(','));
            if (sptp!== '') {
              let picture =sptp.split(',');
              picture.forEach((item,index)=>{
                console.log('item',item)
                let pic = {
                  name:'',
                  url:item
                }
                this.fileList.push(pic);
              })

            }
            console.log('form',this.form);
            this.listLoading = false
          } else {
            // this.loading = false
            this.$message({
              message: response.data.reason.text,
              type: 'error'
            })
          }
        })
      },
      // 列表
      fetchData() {
        const page = {
          currentPage: this.currentPage,
          currentResult: 0,
          entityOrField: true,
          pageStr: 'string',
          pd: {
            zdbh: '',
          },
          showCount: this.showCount,
          totalPage: 0,
          totalResult: 0
        }

        const params = {}
        this.listLoading = true
        getSpfls(params).then(response => {
          if (response.data.error === null) {
            this.spfls = response.data.data.list
            this.listLoading = false
          } else {
            // this.loading = false
            this.$message({
              message: response.data.error.text,
              type: 'error'
            })
          }
        })


      },
      /*发布*/
      draftForm() {
        if (this.form.jdbt.length === 0 || this.from.title.jdms === 0) {
          this.$message({
            message: '请填写必要的标签和内容',
            type: 'warning'
          })
          return
        }
        this.$message({
          message: '保存成功',
          type: 'success',
          showClose: true,
          duration: 1000
        })
        this.from.status = 'draft'
      },
      // 新增
      submitForm: function() {
        console.log("文件列表"+this.fileList);
        let self = this;
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.addLoading = true
              // NProgress.start();
              console.log(this.form);
              const para = Object.assign({}, this.form)
              console.log('para', para);
              let id= this.form.id;
              if (id !== undefined && id !== null && id !== '') {//更新
                updateGoods(para).then((res) => {
                  console.log("res");
                  console.log(res);
                  this.addLoading = false
                  // NProgress.done();
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  })
                  // this.$refs['from'].resetFields()
                  // this.fetchData()
                }).catch(function (error) {
                  // 处理 getJSON 和 前一个回调函数运行时发生的错误
                  self.addLoading = false;
                  // console.log('发生错误！', error);
                  // self.$message({
                  //   message: '发生错误：'+error,
                  //   type: 'error'
                  // })

                })
              }else {
                //新增
                addGoods(para).then((res) => {
                  console.log("res");
                  console.log(res);
                  this.addLoading = false
                  // NProgress.done();
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  })
                  // this.$refs['from'].resetFields()
                  // this.fetchData()
                }).catch(function (error) {
                  self.addLoading = false;
                  console.log('发生错误！', error);
                  //已由拦截器提醒
                  // self.$message({
                  //   message: '发生错误 ：'+error,
                  //   type: 'error'
                  // })

                })
              }
            })
          }
        })
      },
      //
/*      onSelectedDrug : function(value){
        let obj = {};
        obj = this.fxlxDicts.find((item)=>{
          return item.code === value;
        });

        this.form.fxlx_mc = obj.name;
        console.log('发现类型名称',this.form.fxlx_mc)
      },*/
      goback(){
        this.$router.go(-1);//返回上一层
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
        console.log('delfile',file);
        let para = {
          fileurl:file.url
        };
        delFile(para).then((res) => {
         console.log('删除返回值',res);
        let sptp = this.form.sptp;
        console.log('picture',sptp.split(','));
        if (sptp!== '') {
          let picture =sptp.split(',');
          picture.forEach((item,index)=>{
            console.log('item',item)
            if (file.url === item) {
              picture.splice(index,1);
              this.form.sptp = picture.join(',');
              console.log('删除后的图片',this.form.sptp)
            }
          })
        }
        });

      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        this.$message.warning(`最多可上传 3 个文件！`);
      },
      beforeRemove(file, fileList) {
        return true;
        // return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleAvatarSuccess(res, file) {
        console.log(res,res.data.url);
        console.log(file, file.url);
        console.log('file.url',file.url);
        if(this.form.sptp==''){
          this.form.sptp = res.data.url;
        }else {
          this.form.sptp =   this.form.sptp +','+res.data.url;
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isGIF = file.type === 'image/gif';
        const isPNG = file.type === 'image/png';
        const isBMP = file.type === 'image/bmp';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG && !isGIF && !isPNG && !isBMP) {
          this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return (isJPG || isBMP || isGIF || isPNG) && isLt2M;
      }


    }
  }
</script>


<style rel="stylesheet/scss" lang="scss" scoped>
  @import "~@/styles/mixin.scss";
  .createPost-container {
    position: relative;
    .createPost-main-container {
      padding: 40px 45px 20px 50px;
      .postInfo-container {
        position: relative;
        @include clearfix;
        margin-bottom: 10px;
        .postInfo-container-item {
          float: left;
        }
      }
      .editor-container {
        min-height: 500px;
        margin: 0 0 30px;
        .editor-upload-btn-container {
          text-align: right;
          margin-right: 10px;
          .editor-upload-btn {
            display: inline-block;
          }
        }
      }
    }
    .word-counter {
      width: 40px;
      position: absolute;
      right: -10px;
      top: 0px;
    }
  }

  .sub-navbar {
    height: 50px;
    line-height: 50px;
    position: relative;
    width: 100%;
    text-align: right;
    padding-right: 20px;
    transition: 600ms ease position;
    background: linear-gradient(90deg, rgba(32, 182, 249, 1) 0%, rgba(32, 182, 249, 1) 0%, rgba(33, 120, 241, 1) 100%, rgba(33, 120, 241, 1) 100%);
    .subtitle {
      font-size: 20px;
      color: #fff;
    }
    &.draft {
      background: #d0d0d0;
    }
    &.deleted {
      background: #d0d0d0;
    }
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 0px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>


